//
//  OALoginViewController.m
//  maocuhuiOASystem
//
//  Created by michael on 16/3/20.
//  Copyright © 2016年 czd. All rights reserved.
//

#import "OALoginViewController.h"
#import "MainViewController.h"
#import "XmlParseHelper.h"
#import "AuthHelper.h"
#import "webViewController.h"
#import "MainTabBarController.h"

@interface OALoginViewController ()<UITextFieldDelegate,SangforSDKDelegate>
@property (nonatomic, strong) AuthHelper *helper;
@property(nonatomic,strong)NSArray * array;
@property(nonatomic,strong)NSDictionary * dic2;
@end

@implementation OALoginViewController
short port = 443;                        //vpn设备端口号，一般为443
NSString *vpnIp =    @"122.224.123.170";  //vpn设备IP地址
//NSString *userName = @"fly5";             //用户名认证的用户名
//NSString *password = @"12345678";                //用户名认证的密码

NSString *userName = @"ccpitzjapp";             //用户名认证的用户名
NSString *password = @"ccpitzjappapp";

NSString *certName = @"";     //导入证书名字，如果服务端没有设置证书认证可以不设置
NSString *certPwd =  @"";          //证书密码，如果服务端没有设置证书


- (void)viewDidLoad {

//_helper = [[AuthHelper alloc] initWithHostAndPort:vpnIp port:port delegate:self];
//
//    [self.helper setAuthParam:@AUTO_LOGIN_OFF_KEY param:@"true"];


    [super viewDidLoad];
    self.rememberbutton.selected = YES;
        // Do any additional setup after loading the view.

    UIImageView *image1 = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"密码"]];
      image1.frame = CGRectMake(10, 5, 20, 20);
    
//image1.transform = CGAffineTransformMakeTranslation(30, 0);
       //image1.contentMode = UIViewContentModeTopLeft;
   UIView *view1 = [[UIView alloc]init];
   view1.backgroundColor = [UIColor whiteColor];
   view1.size = CGSizeMake(30,30);
   [view1 addSubview:image1];
    self.passwordTextField.leftView = view1;
    self.passwordTextField.leftViewMode = UITextFieldViewModeAlways;
UIImageView *image2 = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"用户名"]];
 image2.frame = CGRectMake(10, 5, 20, 20);
  UIView *view2 = [[UIView alloc]init];
   view2.backgroundColor = [UIColor whiteColor];
   view2.size = CGSizeMake(30,30);
   [view2 addSubview:image2];

 
    self.accountTextField.leftView = view2;
    self.accountTextField.leftViewMode = UITextFieldViewModeAlways;

 if ([[[NSUserDefaults standardUserDefaults] objectForKey:@"userId"] length] !=0) {
        self.accountTextField.text = [[NSUserDefaults standardUserDefaults] objectForKey:@"userId"];
    }
    
    if ([[[NSUserDefaults standardUserDefaults] objectForKey:@"pwdId"] length] !=0) {
        self.passwordTextField.text = [[NSUserDefaults standardUserDefaults] objectForKey:@"pwdId"];
    }
    
    if ([[[NSUserDefaults standardUserDefaults] objectForKey:@"autoLogin"] isEqualToString:@"Y"]) {
        self.autobutton.selected = YES;
    }
     // 判断版本
    NSDictionary *infoDictionary = [[NSBundle mainBundle] infoDictionary];
 CFShow((__bridge CFTypeRef)(infoDictionary));
// app名称
 NSString *app_Name = [infoDictionary objectForKey:@"CFBundleDisplayName"];
 // app版本
_verson= [infoDictionary objectForKey:@"CFBundleShortVersionString"];

}

#pragma Mark VPNDelegate
- (void) onCallBack:(const VPN_RESULT_NO)vpnErrno authType:(const int)authType
{
    switch (vpnErrno)
    {
        case RESULT_VPN_INIT_FAIL:
            NSLog(@"Vpn Init failed!");
            break;
            
        case RESULT_VPN_AUTH_FAIL:
            [self.helper clearAuthParam:@SET_RND_CODE_STR];
            NSLog(@"Vpn auth failed!");
            break;
            
        case RESULT_VPN_INIT_SUCCESS:
            NSLog(@"Vpn init success!");
            //设置认证参数 用户名和密码以数值map的形式传入
        
//                    [self.helper setAuthParam:@"ccpitzjapp" param:userName];
//            [self.helper setAuthParam:@"ccpitzjappapp" param:password];
        
            [self.helper setAuthParam:@PORPERTY_NamePasswordAuth_NAME param:userName];
            [self.helper setAuthParam:@PORPERTY_NamePasswordAuth_PASSWORD param:password];
            //开始用户名密码认证
            [self.helper loginVpn:SSL_AUTH_TYPE_PASSWORD];
            break;
        case RESULT_VPN_AUTH_SUCCESS:
            [self startOtherAuth:authType];
            break;
        case RESULT_VPN_AUTH_LOGOUT:
            NSLog(@"Vpn logout success!");
//            exit(0);
            break;
        case RESULT_VPN_OTHER:
            if (VPN_OTHER_RELOGIN_FAIL == (VPN_RESULT_OTHER_NO)authType) {
                NSLog(@"Vpn relogin failed, maybe network error");
            }
            break;
            
        case RESULT_VPN_NONE:
            break;
            
        default:
            break;
    }
}

- (void) startOtherAuth:(const int)authType
{
    NSArray *paths = nil;
    switch (authType)
    {
        case SSL_AUTH_TYPE_CERTIFICATE:
            paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
                                                        NSUserDomainMask, YES);
            
            if (nil != paths && [paths count] > 0)
            {
                NSString *dirPaths = [paths objectAtIndex:0];
                NSString *authPaths = [dirPaths stringByAppendingPathComponent:certName];
                NSLog(@"PATH = %@",authPaths);
                [self.helper setAuthParam:@CERT_P12_FILE_NAME param:authPaths];
                [self.helper setAuthParam:@CERT_PASSWORD param:certPwd];
            }
            NSLog(@"Start Cert Auth!!!");
            break;
            
        case SSL_AUTH_TYPE_PASSWORD:
            NSLog(@"Start Password Name Auth!!!");
            [self.helper setAuthParam:@PORPERTY_NamePasswordAuth_NAME param:userName];
            [self.helper setAuthParam:@PORPERTY_NamePasswordAuth_PASSWORD param:password];
            
            break;
        case SSL_AUTH_TYPE_NONE:
            NSLog(@"Auth success!!!");
          //  [self upApp];
        
            [self setin];
            return;
        default:
            NSLog(@"Other failed!!!");
            return;
    }
    [self.helper loginVpn:authType];
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField{
    [textField resignFirstResponder];
    return YES;
}
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{

    [self.accountTextField resignFirstResponder];
    [self.passwordTextField resignFirstResponder];
}




- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
- (void)setin{
[self.accountTextField resignFirstResponder];
[self.passwordTextField resignFirstResponder];
 if (self.accountTextField.text.length == 0) {
        [self.view makeToast:@"请输入账号"];
        return;
    }
    if (self.passwordTextField.text.length == 0) {
        [self.view makeToast:@"请输入密码"];
        return;
    }
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    NSString *strUrl = [self.accountTextField.text stringByReplacingOccurrencesOfString:@" " withString:@""];
    NSMutableDictionary * params = [NSMutableDictionary dictionary];
    [params setObject:self.accountTextField.text forKey:@"userId"];
     [params setObject:self.passwordTextField.text forKey:@"pwdId"];
//        NSString *json =[NSString stringWithFormat:@"{\"action':'login','service':'UserService','userName':'%@','password':'%@','vaueJson':'{username:%@,password:%@}\"}",strUrl,self.passwordTextField.text,self.accountTextField.text,self.passwordTextField.text];

    NSString *json =[NSString stringWithFormat:@"{\"action\":\"login\",\"service\":\"UserService\",\"userName\":\"%@\",\"password\":\"%@\",\"vaueJson\":\"{'username':'%@','password':'%@'}\"}",strUrl,self.passwordTextField.text,self.accountTextField.text,self.passwordTextField.text];

 NSArray * array = @[@{@"arg0":json}];
    
[HttpTools requestWithURL:BaseURL arrays:array method:Basemethod success:^(id JSON) {
       [MBProgressHUD hideAllHUDsForView:self.view animated:YES];
    
    if ([JSON[@"result"] isEqualToString:@"success"]){
    
               MainTabBarController *tar = [[MainTabBarController alloc]init];
               self.view.window.rootViewController = tar;
               [[NSUserDefaults standardUserDefaults] setObject:JSON[@"userid"] forKey:@"userHumber"];
                if (self.rememberbutton.selected) {
                    [[NSUserDefaults standardUserDefaults] setObject:strUrl forKey:@"userId"];
                    [[NSUserDefaults standardUserDefaults] setObject:self.passwordTextField.text forKey:@"pwdId"];
                   
                 
                }else{
                    [[NSUserDefaults standardUserDefaults] setObject:@"" forKey:@"userId"];
                    [[NSUserDefaults standardUserDefaults] setObject:@"" forKey:@"pwdId"];
                    
                }
                
                if (!self.autobutton.selected) {
                    [[NSUserDefaults standardUserDefaults] setObject:@"N" forKey:@"autoLogin"];
                }else{
                    [[NSUserDefaults standardUserDefaults] setObject:@"Y" forKey:@"autoLogin"];
                }
                 [self.view makeToast:JSON[@"reason"]];

}
                else{
                   [self.view makeToast:JSON[@"reason"]];
    }
        
    } failure:^(NSError *error) {
         [MBProgressHUD hideAllHUDsForView:self.view animated:YES];
    }];
}
- (IBAction)LoginAction:(id)sender {


if (self.accountTextField.text.length == 0) {
        [self.view makeToast:@"请输入账号"];
        return;
    }
    if (self.passwordTextField.text.length == 0) {
        [self.view makeToast:@"请输入密码"];
        return;
    }
else{
 MBProgressHUD * hud =  [MBProgressHUD showHUDAddedTo:self.view animated:YES];
                hud.labelText = @"正在登陆,请稍等";
                if ([_helper queryVpnStatus] ==VPN_STATUS_OK){
                [self setin];
                }
                else{
                 self.helper = [[AuthHelper alloc] initWithHostAndPort:vpnIp port:port delegate:self];
    [self.helper setAuthParam:@AUTO_LOGIN_OFF_KEY param:@"true"];
}
                }


//[NSThread sleepForTimeInterval:1.0];
//                 [self setin];

    

 
}
- (IBAction)rememberbutton:(id)sender {
 self.rememberbutton.selected = !self.rememberbutton.selected;
    if (!self.rememberbutton.selected) {
        self.autobutton.selected = self.rememberbutton.selected;
    }
    

}

- (IBAction)autonbutton:(id)sender {
    self.autobutton.selected = !self.autobutton.selected;


//在此实现不打勾时的方法
}
@end
